﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YJTShiftManagement.Utils
{
    public class Common
    {
        /// <summary>
        /// 从文件读取转义base64
        /// </summary>
        /// <param name="path"></param>
        /// <returns>返回base64</returns>
        public static string GetBase64FromFile(string path)
        {
            using (FileStream filestream = new FileStream(path, FileMode.Open))
            {
                byte[] bt = new byte[filestream.Length];

                //调用read读取方法
                filestream.Read(bt, 0, bt.Length);
                var base64Str = Convert.ToBase64String(bt);

                return "data:image/png;base64," + base64Str;
            }
        }
        /// <summary>
        /// ToDecimal
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static decimal ToDecimal(string source)
        {
            decimal o;
            return decimal.TryParse(source, out o) ? o : 0;
        }

        /// <summary>
        /// ToDecimal
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static double ToDouble(string source)
        {
            double o;
            return double.TryParse(source, out o) ? o : 0;
        }

        /// <summary>
        /// ToDecimal
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static int ToInt(string source)
        {
            int o;
            return int.TryParse(source, out o) ? o : 0;
        }

        public static DateTime ToDt(string source)
        {
            DateTime dt;
            return DateTime.TryParse(source, out dt) ? dt : DateTime.MaxValue;
        }

        /// <summary>
        /// 遮挡中间字符
        /// </summary>
        /// <param name="source"></param>
        /// <param name="number">遮挡中间多少个</param>
        /// <returns></returns>
        public static string HideMiddle(string source, int number)
        {
            if (string.IsNullOrWhiteSpace(source)) return string.Empty;
            string star = string.Empty;
            if (source.Length <= number)
            {
                for (int i = 0; i < source.Length; i++) star += "*";
                return star;
            }
            else
            {
                for (int i = 0; i < number; i++) star += "*";
            }

            int mod = (source.Length - number) % 2;
            int leftSum = 0;
            int rightSum = 0;
            if (mod == 0)
            {
                // 如果是偶数 则等分
                leftSum = (source.Length - number) / 2;
                rightSum = leftSum;
            }
            else
            {
                // 如果是奇数，则前面多1，后面少1
                leftSum = (source.Length - number) / 2;
                rightSum = source.Length - number - leftSum;
            }

            return source.Substring(0, leftSum) + star + source.Substring(source.Length - rightSum, rightSum);

        }


        public static void UpdateSettingString(string settingName, string valueName)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            if (ConfigurationManager.AppSettings[settingName] != null)
            {
                config.AppSettings.Settings.Remove(settingName);
            }
            config.AppSettings.Settings.Add(settingName, valueName);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        public static string GetSettingString(string settingName)
        {
            try
            {
                if (ConfigurationManager.AppSettings[settingName] == null)
                {
                    return null;
                }
                string settingString = ConfigurationManager.AppSettings[settingName].ToString();
                return settingString;
            }
            catch (Exception)
            {
                return null;
            }
        }


        #region --  身份证校验
        /// <summary> 
        /// 验证身份证合理性 
        /// </summary> 
        /// <param name="Id"></param> 
        /// <returns></returns> 
        public static bool CheckIDCard(string idNumber)
        {
            // 20211008 bywei  由于某些身份证号是真实身份证号但又不满足校验规则，所以先把这个规则去掉
            return true;
            //if (idNumber.Length == 18)
            //{
            //    bool check = CheckIDCard18(idNumber);
            //    return check;
            //}
            //else if (idNumber.Length == 15)
            //{
            //    bool check = CheckIDCard15(idNumber);
            //    return check;
            //}
            //else
            //{
            //    return false;
            //}
        }


        /// <summary> 
        /// 18位身份证号码验证 
        /// </summary> 
        private static bool CheckIDCard18(string idNumber)
        {
            long n = 0;
            if (long.TryParse(idNumber.Remove(17), out n) == false
                || n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证 
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(idNumber.Remove(2)) == -1)
            {
                return false;//省份验证 
            }
            string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证 
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = idNumber.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower())
            {
                return false;//校验码验证 
            }
            return true;//符合GB11643-1999标准 
        }


        /// <summary> 
        /// 16位身份证号码验证 
        /// </summary> 
        private static bool CheckIDCard15(string idNumber)
        {
            long n = 0;
            if (long.TryParse(idNumber, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证 
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(idNumber.Remove(2)) == -1)
            {
                return false;//省份验证 
            }
            string birth = idNumber.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证 
            }
            return true;
        }
        /// <summary>
        /// 验证是否为18位身份证
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsCard(string input)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(input, @"^(\d{17}[\d|X])");
        }
        /// <summary>
        /// 获取生日
        /// </summary>
        /// <param name="idcard"></param>
        /// <returns></returns>
        public static string GetBirth(string idcard)
        {
            if (string.IsNullOrWhiteSpace(idcard)) return string.Empty;
            if (idcard.Length == 15)
            {
                string birth = idcard.Substring(6, 6).Insert(4, "-").Insert(2, "-");
                DateTime time = new DateTime();
                if (DateTime.TryParse(birth, out time) == true)
                {
                    return birth;
                }
                else
                {
                    return string.Empty;
                }
            }
            else if (idcard.Length == 18)
            {
                string birth = idcard.Substring(6, 8).Insert(6, "-").Insert(4, "-");
                DateTime time = new DateTime();
                if (DateTime.TryParse(birth, out time) == true)
                {
                    return birth;
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
                return string.Empty;
            }
        }

        public static string GetSex(string idcard)
        {
            int n = 0;
            if (string.IsNullOrWhiteSpace(idcard)) return string.Empty;
            if (idcard.Length == 15)
            {
                n = ToInt(idcard.Substring(12, 3));

            }
            else if (idcard.Length == 18)
            {
                n = ToInt(idcard.Substring(14, 3));
            }

            if (n <= 0) return string.Empty;
            if (n % 2 == 0)//性别代码为偶数是女性奇数为男性
            {
                return "女";
            }
            else
            {
                return "男";
            }

        }


        #endregion



        #region -- 自动更新

        public static string GetCurrentVersion()
        {
            string curV = Application.ProductVersion;
            string[] s = curV.Split('.');
            if (s == null) return null;
            if (s.Length != 4) return null;
            return $"{s[0]}{s[1].PadLeft(2, '0')}{s[2].PadLeft(2, '0')}{s[3].PadLeft(2, '0')}";

        }

        // 获取最新版本和版本文件

        // 下载版本文件

        // 解压缩版本文件

        // 杀死进程，启动更新

        // 替换文件

        // 清空临时文件

        // 重启主程序

        #endregion

        #region 引用对象拷贝

        /// <summary>
        /// 对象拷贝
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="obj">对象内容</param>
        /// <returns>拷贝后对象</returns>
        /// <remarks>转换的model需要标记可序列化</remarks>
        public static T Clone<T>(T obj)
        {
            try
            {
                using (Stream stream = new MemoryStream())
                {
                    System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    formatter.Serialize(stream, obj);
                    stream.Seek(0, SeekOrigin.Begin);
                    return (T)formatter.Deserialize(stream);
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }

        /// <summary>
        /// 对象拷贝
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="obj">对象内容</param>
        /// <returns>拷贝后对象</returns>
        /// <remarks>转换的model需要标记可序列化</remarks>
        public static List<T> Clone<T>(List<T> obj)
        {
            try
            {
                using (Stream stream = new MemoryStream())
                {
                    System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    formatter.Serialize(stream, obj);
                    stream.Seek(0, SeekOrigin.Begin);
                    return (List<T>)formatter.Deserialize(stream);
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        #endregion

        #region 字符验证


        /// <summary>
        /// 姓名验证  只允许为中文英文，且不能为数字，不能为空
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool NameCheck(string name)
        {
            return true;
            bool result = false;
            try
            {
                // 空
                if (string.IsNullOrEmpty(name))
                {
                    return result;
                }

                // 中文,英文
                if (!Regex.IsMatch(name, @"^[\u4e00-\u9fa5]{0,}$") && !Regex.IsMatch(name, @"^[A-Za-z]+$"))
                {
                    return result;
                }

                if (Regex.IsMatch(name, @"^[0-9]*$"))
                {
                    return result;
                }

                result = true;
            }
            catch (Exception ex)
            {
                return false;
            }

            return result;
        }

        /// <summary>
        /// 身份证验证 15或18位 不为空 不允许位汉字
        /// </summary>
        /// <param name="card"></param>
        /// <returns></returns>
        public static bool CardCheck(string card)
        {
            return true;

            bool result = false;

            try
            {
                if (string.IsNullOrEmpty(card))
                    return result;

                if (card.Length != 15 && card.Length != 18)
                    return result;

                Regex rg = null;

                if (card.Length == 18)
                {
                    rg = new Regex(@"^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$");
                    if (!rg.IsMatch(card))
                        return result;
                }

                if (card.Length == 15)
                {
                    rg = new Regex(@"^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$");
                    if (!rg.IsMatch(card))
                        return result;
                }
                result = true;
            }
            catch (Exception)
            {
                return false;
            }

            return result;
        }

        /// <summary>
        /// 电话号码验证（手机）
        /// 11位 不允许为空，只能输入数字
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static bool PhoneCheck(string phone)
        {
            bool result = false;
            return true;

            try
            {
                if (string.IsNullOrEmpty(phone))
                    return result;

                if (!System.Text.RegularExpressions.Regex.IsMatch(phone, @"^1[3456789]\d{9}$"))
                    return result;

                result = true;
            }
            catch (Exception ex)
            {
                return false;
            }

            return result;
        }

        /// <summary>
        /// 年龄验证
        /// ①年龄必填 ②年龄只允许输入正整数 ③年龄0-150整数
        /// </summary>
        /// <returns></returns>
        public static bool AgeCheck(string age)
        {
            bool result = false;
            return true;

            try
            {
                if (string.IsNullOrEmpty(age))
                    return result;

                if (!System.Text.RegularExpressions.Regex.IsMatch(age, @"^[1-9]\d*$"))
                    return result;

                int ageValue = Convert.ToInt32(age);

                if (ageValue > 150 || ageValue < 0)
                    return result;

                result = true;
            }
            catch (Exception ex)
            {
                return false;
            }

            return result;
        }

        #endregion
    }
}
